package com.fulizhe.catlocal.integration.springboot.metric;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;

class WebUtil {

	/**
	 * 获取 request 请求内容, 优先取QueryString, 然后是RequestBody
	 *
	 * @param request
	 *            request
	 * @return {String}
	 */
	public static String getRequestContent(HttpServletRequest request) {
		try {
			String queryString = request.getQueryString();
			if (StrUtil.isNotBlank(queryString)) {
				return new String(queryString.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.UTF_8)
						.replaceAll("&amp;", "&").replaceAll("%22", "\"");
			}
			String charEncoding = request.getCharacterEncoding();
			if (charEncoding == null) {
				charEncoding = CharsetUtil.UTF_8;
			}
			byte[] buffer = getRequestBody(request.getInputStream()).getBytes();
			String str = new String(buffer, charEncoding).trim();
			if (StrUtil.isBlank(str)) {
				StringBuilder sb = new StringBuilder();
				Enumeration<String> parameterNames = request.getParameterNames();
				while (parameterNames.hasMoreElements()) {
					String key = parameterNames.nextElement();
					String value = request.getParameter(key);
					sb.append(key);
					sb.append("=");
					sb.append(value);
					sb.append("&");
				}
				str = StrUtil.removeSuffix(sb.toString(), "&");
			}
			return str.replaceAll("&amp;", "&");
		} catch (Exception ex) {
			ex.printStackTrace();
			return StrUtil.EMPTY;
		}
	}

	/**
	 * 获取 request 请求体
	 *
	 * @param servletInputStream
	 *            servletInputStream
	 * @return body
	 */
	public static String getRequestBody(ServletInputStream servletInputStream) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(servletInputStream, StandardCharsets.UTF_8));
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IoUtil.close(servletInputStream);
			IoUtil.close(reader);
		}
		return sb.toString();
	}
}
